package org.xbdframework.dao.support.pagehelper;

import java.util.HashMap;
import java.util.Map;

import org.apache.commons.lang3.ArrayUtils;

import org.xbdframework.dao.core.PageInfo;
import org.xbdframework.jdbc.core.SqlAndParam;

import org.springframework.jdbc.core.namedparam.MapSqlParameterSource;
import org.springframework.jdbc.core.namedparam.SqlParameterSource;

public class MysqlPageHelper extends JdbcPageHelper {

    @Override
    public SqlAndParam<Map<String, Object>> paged(String sql, Map<String, Object> parameters, PageInfo pageInfo) {
        Map<String, Object> temp = new HashMap<>();
        temp.putAll(parameters);

        if ((pageInfo.getPageNum() != 1) && (pageInfo.getPageNum() != 0)) {
            String pSql = sql + " limit :startRow_, :pageSize_";
            temp.put("startRow_", pageInfo.getStartRow());
            temp.put("pageSize_", pageInfo.getPageSize());
            return new SqlAndParam<>(pSql, temp);
        }

        String pSql = sql + " limit :pageSize_";
        temp.put("pageSize_", pageInfo.getPageSize());

        return new SqlAndParam<>(pSql, temp);
    }

    @Override
    public SqlAndParam<SqlParameterSource> paged(String sql, SqlParameterSource parameters, PageInfo pageInfo) {
        MapSqlParameterSource temp = buildParameters(parameters);

        if ((pageInfo.getPageNum() != 1) && (pageInfo.getPageNum() != 0)) {
            String pSql = sql + " limit :startRow_, :pageSize_";
            temp.addValue("startRow_", pageInfo.getStartRow());
            temp.addValue("pageSize_", pageInfo.getPageSize());
            return new SqlAndParam<>(pSql, temp);
        }

        String pSql = sql + " limit :pageSize_";
        temp.addValue("pageSize_", pageInfo.getPageSize());
        return new SqlAndParam<>(pSql, temp);
    }

    @Override
    public SqlAndParam<Object[]> paged(String sql, Object[] parameters, PageInfo pageInfo) {
        if ((pageInfo.getPageNum() != 1) && (pageInfo.getPageNum() != 0)) {
            String pSql = sql + " limit ?, ?";

            Object[] tempArray = ArrayUtils.add(parameters, pageInfo.getStartRow());
            tempArray = ArrayUtils.add(tempArray, pageInfo.getPageSize());

            return new SqlAndParam<>(pSql, tempArray);
        }

        String pSql = sql + " limit ?";
        Object[] tempArray = ArrayUtils.add(parameters, pageInfo.getPageSize());

        return new SqlAndParam<>(pSql, tempArray);
    }
}
